import React, { useState } from 'react';
import {checkSafety, diagnoseDeadlock, explainSafety} from '../services/api';
import MatrixInput from './MatrixInput';
import DimensionsSelector from './DimensionsSelector';
import ProcessInput from './ProcessInput';

const ApiTabs = ({ state, onStateChange }) => {
    const [activeTab, setActiveTab] = useState('explain');
    const [deadlockProcesses, setDeadlockProcesses] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);

    // 状态变量
    const [safetyCheckResult, setSafetyCheckResult] = useState(null); // 存储安全检查结果
    const [algorithmExplanation, setAlgorithmExplanation] = useState(null); // 算法解释
    const [diagnosisExplanation, setDiagnosisExplanation] = useState(null); // 死锁诊断解释

    const updateDimensions = (processCount, resourceTypeCount) => {
        const validDeadlockProcesses = deadlockProcesses.filter(pid => pid < processCount);

        // 更新死锁进程选择状态
        setDeadlockProcesses(validDeadlockProcesses);
        onStateChange({
            ...state,
            processCount,
            resourceTypeCount,
            maxMatrix: initializeMatrix(processCount, resourceTypeCount),
            allocationMatrix: initializeMatrix(processCount, resourceTypeCount),
            availableVector: Array(resourceTypeCount).fill(0)
        });


    };

    const initializeMatrix = (rows, cols) => {
        return Array(rows).fill().map(() => Array(cols).fill(0));
    };

    const updateMatrix = (matrixName, matrix) => {
        onStateChange({ ...state, [matrixName]: matrix });
    };

    // 处理安全检测 - 只调用后端算法接口
    const handleCheckSafety = async () => {
        setIsLoading(true);
        setError(null);
        setSafetyCheckResult(null); // 重置结果

        try {
            // 执行安全检查
            const result = await checkSafety(state);
            setSafetyCheckResult(result);
        } catch (err) {
            setError(err.response?.data?.error || '执行安全检查失败');
        } finally {
            setIsLoading(false);
        }
    };

    // 处理算法流程解释 - 只调用AI接口
    const handleExplainAlgorithm = async () => {
        setIsLoading(true);
        setError(null);
        setAlgorithmExplanation(null); // 重置解释

        try {
            // 调用AI接口获取算法流程解释
            const explanation = await explainSafety(state, null);
            setAlgorithmExplanation(explanation);
            setActiveTab('algorithm-explanation');
        } catch (err) {
            setError(err.response?.data?.error || '获取算法解释失败');
        } finally {
            setIsLoading(false);
        }
    };

    const handleDiagnoseDeadlock = async () => {
        setIsLoading(true);
        setError(null);
        setDiagnosisExplanation(null); // 重置诊断结果
        // 过滤掉无效的进程ID（不在0到state.processCount-1之间的ID）
        const validProcessIds = deadlockProcesses.filter(pid =>
            pid >= 0 && pid < state.processCount
        );

        // 如果没有有效的进程ID，则提示错误
        if (validProcessIds.length === 0) {
            setError('请选择有效的进程ID');
            setIsLoading(false);
            return;
        }

        try {
            // 调用死锁诊断接口
            const response = await diagnoseDeadlock(state, deadlockProcesses);
            setDiagnosisExplanation(response.diagnosis);
        } catch (err) {
            setError(err.message || '诊断死锁失败');
        } finally {
            setIsLoading(false);
        }
    };

    // 渲染算法流程解释面板
    const renderAlgorithmExplanation = () => {
        if (!algorithmExplanation) return <p>未获取到算法解释</p>;

        // 确保 explanation 是字符串类型
        const algoExplanation = typeof algorithmExplanation === 'string'
            ? algorithmExplanation
            : (algorithmExplanation || "");

        return (
            <div className="algorithm-explanation">
                <div className="explanation-container">
                    <h3>银行家算法流程解释</h3>
                </div>
                <div className="explanation-content">
                    {algoExplanation.split('\n').map((paragraph, idx) => (
                        <p key={`algo-exp-${idx}`}>{paragraph}</p>
                    ))}
                </div>
            </div>
        );
    };

    return (
        <div className="api-tabs">
            <div className="tab-buttons">
                <button
                    className={activeTab === 'explain' ? 'active' : ''}
                    onClick={() => setActiveTab('explain')}
                >
                    安全检测
                </button>
                <button
                    className={activeTab === 'diagnose' ? 'active' : ''}
                    onClick={() => setActiveTab('diagnose')}
                >
                    死锁诊断
                </button>
                <button
                    className={activeTab === 'algorithm-explanation' ? 'active' : ''}
                    disabled={!algorithmExplanation}
                    onClick={() => setActiveTab('algorithm-explanation')}
                >
                    算法流程
                </button>
            </div>

            <div className="tab-content">
                {activeTab === 'algorithm-explanation' ? renderAlgorithmExplanation() : (
                    <>
                        <div className="dimensions-section">
                            <DimensionsSelector
                                processCount={state.processCount}
                                resourceTypeCount={state.resourceTypeCount}
                                onProcessCountChange={(count) => updateDimensions(count, state.resourceTypeCount)}
                                onResourceTypeChange={(count) => updateDimensions(state.processCount, count)}
                            />
                        </div>

                        {activeTab === 'explain' ? (
                            <div className="explain-tab">
                                <MatrixInput
                                    title="最大需求矩阵 (Max Matrix)"
                                    matrix={state.maxMatrix}
                                    onMatrixChange={(matrix) => updateMatrix('maxMatrix', matrix)}
                                    dimensions={{ rows: state.processCount, cols: state.resourceTypeCount }}
                                />

                                <MatrixInput
                                    title="已分配矩阵 (Allocation Matrix)"
                                    matrix={state.allocationMatrix}
                                    onMatrixChange={(matrix) => updateMatrix('allocationMatrix', matrix)}
                                    dimensions={{ rows: state.processCount, cols: state.resourceTypeCount }}
                                />

                                <div className="vector-section">
                                    <h3>可用资源向量 (Available Vector)</h3>
                                    <div className="vector-input">
                                        {[...Array(state.resourceTypeCount)].map((_, i) => (
                                            <div key={`vector-${i}`} className="vector-item">
                                                <span>资源 {i + 1}:</span>
                                                <input
                                                    type="number"
                                                    min="0"
                                                    value={state.availableVector[i] || 0}
                                                    onChange={(e) => {
                                                        const value = isNaN(parseInt(e.target.value)) ? 0 : parseInt(e.target.value);
                                                        const newVector = [...state.availableVector];
                                                        newVector[i] = value;
                                                        onStateChange({ ...state, availableVector: newVector });
                                                    }}
                                                />
                                            </div>
                                        ))}
                                    </div>
                                </div>

                                <div className="action-buttons">
                                    <button
                                        className="submit-btn primary"
                                        onClick={handleCheckSafety}
                                        disabled={isLoading}
                                    >
                                        {isLoading ? '正在执行安全检查...' : '执行安全检测'}
                                    </button>

                                    <button
                                        className="submit-btn secondary"
                                        onClick={handleExplainAlgorithm}
                                        disabled={isLoading}
                                    >
                                        {isLoading ? '正在获取解释...' : '解释算法流程'}
                                    </button>
                                </div>

                                {safetyCheckResult && (
                                    <div className="safety-result">
                                        <div className={`status-badge ${safetyCheckResult.safe ? 'safe' : 'unsafe'}`}>
                                            {safetyCheckResult.safe ?
                                                <div className="badge-content">
                                                    <span className="icon">✓</span>
                                                    <span>系统安全</span>
                                                </div> :
                                                <div className="badge-content">
                                                    <span className="icon">⚠️</span>
                                                    <span>系统不安全</span>
                                                </div>
                                            }
                                        </div>

                                        {safetyCheckResult.safeSequence && (
                                            <div className="safe-sequence">
                                                <h4>安全序列:</h4>
                                                <div className="sequence-display">
                                                    {safetyCheckResult.safeSequence.map((process, idx) => (
                                                        <React.Fragment key={idx}>
                                                            <span className="process-badge">P{process}</span>
                                                            {idx < safetyCheckResult.safeSequence.length - 1 && (
                                                                <span className="arrow">→</span>
                                                            )}
                                                        </React.Fragment>
                                                    ))}
                                                </div>
                                            </div>
                                        )}

                                        {safetyCheckResult.unmetProcesses && safetyCheckResult.unmetProcesses.length > 0 && (
                                            <div className="unsafe-details">
                                                <h4>无法满足的进程:</h4>
                                                <div className="unsafe-processes">
                                                    {safetyCheckResult.unmetProcesses.map(process => (
                                                        <span key={process} className="process-badge error">P{process}</span>
                                                    ))}
                                                </div>
                                            </div>
                                        )}

                                        {safetyCheckResult.explanation && (
                                            <div className="result-explanation">
                                                <h4>详细解释:</h4>
                                                <div className="explanation-content">
                                                    {safetyCheckResult.explanation}
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                )}

                                {error && <div className="error-message">{error}</div>}
                            </div>
                        ) : (
                            <div className="diagnose-tab">
                                <div className="diagnose-instructions">
                                    <p>请选择可能涉及死锁的进程：</p>
                                    <p className="note">注意：只有在安全检测结果显示系统不安全时，才能进行死锁诊断</p>
                                </div>

                                <ProcessInput
                                    processCount={state.processCount}
                                    deadlockProcesses={deadlockProcesses}
                                    onProcessesChange={setDeadlockProcesses}
                                />

                                <button
                                    className="submit-btn"
                                    onClick={handleDiagnoseDeadlock}
                                    disabled={isLoading || deadlockProcesses.length === 0}
                                >
                                    {isLoading ? '正在诊断...' : '执行死锁诊断'}
                                </button>

                                {diagnosisExplanation && (
                                    <div className="diagnosis-result">
                                        <h3>死锁诊断结果</h3>
                                        <div className="explanation-content">
                                            {typeof diagnosisExplanation === 'string' ?
                                                diagnosisExplanation.split('\n').map((paragraph, idx) => (
                                                    <p key={`diagnosis-exp-${idx}`}>{paragraph}</p>
                                                )) :
                                                <p>{diagnosisExplanation.toString()}</p>
                                            }
                                        </div>
                                    </div>
                                )}

                                {error && <div className="error-message">{error}</div>}
                            </div>
                        )}
                    </>
                )}
            </div>
        </div>
    );
};


export default ApiTabs;